import Router from 'vue-router';
import Vue from 'vue';
Vue.use(Router)


window.$glob = {
  url: '',
  params: {},
  query: {},
  header: {}
};

function getGlobParams() {
  var query = window.location.search.substring(1);
  query = query.split("&");
  query.forEach(ele => {
    var pair = ele.split("=");
    window.$glob.params[pair[0]] = pair[1]
  })
}

const vueRouter = new Router({
  base: process.env.VUE_APP_PATH,
  mode: process.env.VUE_APP_MODE,
  routes: [{
    path: '/',
    component: () => import( /* webpackChunkName: "page" */ '@/page/index'),
    children: [{
      path: '',
      component: () => import( /* webpackChunkName: "page" */ '@/page/list'),
    },
    {
      path: 'category',
      component: () => import( /* webpackChunkName: "page" */ '@/page/list/category'),
    }, {
      path: 'db',
      component: () => import( /* webpackChunkName: "page" */ '@/page/list/db'),
    }, {
      path: 'map',
      component: () => import( /* webpackChunkName: "page" */ '@/page/list/map'),
    }, {
      path: 'document',
      component: () => import( /* webpackChunkName: "page" */ '@/page/list/document'),
    }, {
        path: 'components',
        component: () => import( /* webpackChunkName: "page" */ '@/page/list/components'),
    }, {
      path: 'record',
      component: () => import( /* webpackChunkName: "page" */ '@/page/list/record'),

      }]
  }, {
    path: '/create',
    name: 'create',
    component: () =>
      import( /* webpackChunkName: "page" */ '@/page/create')
  }, {
    path: '/build/:id',
    name: 'build',
    component: () =>
      import( /* webpackChunkName: "page" */ '@/page/build')
  }, {
    path: '/view/:id',
    name: 'view',
    component: () =>
      import( /* webpackChunkName: "page" */ '@/page/view')
  }]
})

// 全局导航守卫
vueRouter.beforeEach((to, from, next) => {
  // 获取 token，这里假设你将 token 存储在 localStorage 中
  getGlobParams();
  let token = window.$glob.params.token
  if (token) {
    localStorage.setItem('token', token);
  }else {
    token = localStorage.getItem('token');
  }
  if (token) {
    // 为目标路由添加 token 参数
    if (!to.query.token) {
      next({
        path: to.path,
        query: { ...to.query, token } // 将 token 添加到 query 参数中
      });

    } else {
      next();
    }
  } else {
    // 如果没有 token，直接跳转
    next();
  }
});

export default vueRouter;
